package hz.mobileproject.pda.toolsmanager.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

import hz.mobileproject.pda.R;
import hz.mobileproject.pda.app.MainApp;
import hz.mobileproject.pda.entity.request.Request_loadPoliceInfo;
import hz.mobileproject.pda.entity.response.Response_loadPoliceInfo;
import hz.mobileproject.pda.entity.response.Response_login_user;
import hz.mobileproject.pda.listener.CustomNetCallBack;
import hz.mobileproject.pda.network.Constance;
import hz.mobileproject.pda.toolsmanager.adapter.ToolsRecyclerAlreadyLVAdaper;
import hz.mobileproject.pda.toolsmanager.adapter.ToolsRecyclerWaitLVAdaper;
import hz.mobileproject.pda.toolsmanager.adapter.ToolsStockAdapter;
import hz.mobileproject.pda.toolsmanager.bean.ToolRecyclerItemBean;
import hz.mobileproject.pda.toolsmanager.bean.request.RQ_FreeCountTool;
import hz.mobileproject.pda.toolsmanager.bean.request.RQ_RecyclerTool;
import hz.mobileproject.pda.toolsmanager.bean.response.RP_BorrowedTool;
import hz.mobileproject.pda.toolsmanager.bean.response.RP_FreeCountTools;
import hz.mobileproject.pda.toolsmanager.bean.response.RP_ToolSysSet;
import hz.mobileproject.pda.toolsmanager.bean.response.RQ_Recycler_Return_Tool;
import hz.mobileproject.pda.ui.base.BaseScanActivity;
import hz.mobileproject.pda.utils.HttpRqUtils;
import hz.mobileproject.pda.utils.TextViewUtil;

/**
 * 工具归还
 */
@ContentView(R.layout.activity_tool_recycler)
public class ToolRecyclerActivity extends BaseScanActivity implements ToolsRecyclerAlreadyLVAdaper.OnDeleteClickListener {

    @ViewInject(R.id.lv_daihuishou)
    private ListView lv_tools_retrieve_wait;
    @ViewInject(R.id.tv_guihuan_person)
    private TextView tv_guihuan_person;
    @ViewInject(R.id.tv_jinban_person)
    private TextView tv_jinban_person;
    @ViewInject(R.id.lv_yihuishou)
    private ListView lv_tools_retrieve_already;
    @ViewInject(R.id.lv_tools_stock)
    private ListView lv_tools_stock;

    private List<ToolRecyclerItemBean> items = new ArrayList<>();


    private ToolsRecyclerWaitLVAdaper mWaitLVAdaper;
    private ToolsRecyclerAlreadyLVAdaper mAlreadyLVAdaper;
    private ToolsStockAdapter mToolsStockAdapter;


    private static final int REQUEST_CODE_POLICE = 0x1085;   //接收人
    private static final int REQUEST_CODE_PRISONER = 0x1086;   //归还人
    private static final int REQUEST_CODE_TOOLS = 0x1087;
    //当前民警信息
    private Response_loadPoliceInfo mPoliceInfo;   //接收人
    private Response_loadPoliceInfo mGuiHuanPerson;   //归还人

    //获取配置
    private RP_ToolSysSet mToolSystemSet;
    private Gson mGson;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initData() {
        setTitle("工具归还");
        mGson = new Gson();
        ToolRecyclerItemBean bean = null;
        for(int i = 0; i < 10;i++) {
            bean = new ToolRecyclerItemBean("类型" + i, "名称" + i);
            items.add(bean);
        }

        mWaitLVAdaper = new ToolsRecyclerWaitLVAdaper(this, new ArrayList<RP_BorrowedTool>());
        lv_tools_retrieve_wait.setAdapter(mWaitLVAdaper);
        mAlreadyLVAdaper = new ToolsRecyclerAlreadyLVAdaper(this, new ArrayList<RP_BorrowedTool>());
        lv_tools_retrieve_already.setAdapter(mAlreadyLVAdaper.setOnDeleteClickListener(this));
        mToolsStockAdapter = new ToolsStockAdapter(this, new ArrayList<RP_FreeCountTools>());
        lv_tools_stock.setAdapter(mToolsStockAdapter);


        mToolSystemSet = (RP_ToolSysSet) getIntent().getSerializableExtra("key");
        //扫描民警
        scanPolice();
    }



    @Override
    protected void onScanSucesess(int requestCode, String scanMsg) {
        LogUtils.e(scanMsg);
        switch (requestCode) {
            case REQUEST_CODE_POLICE:
                getPliceInfoFromSer(scanMsg);
                break;
            case REQUEST_CODE_PRISONER:   //扫描借用人
                getPrisonerInfoFromSer(scanMsg);
                break;

            case REQUEST_CODE_TOOLS:   //扫描工具
                changeToolsStatus(scanMsg);
                break;
        }

    }

    /**
     * 将待归还放入已归还
     * @param scanMsg
     */
    private void changeToolsStatus(String scanMsg) {
        scanMsg = scanMsg.indexOf(mToolSystemSet.getToolPrefix()) == 0 ? scanMsg.substring(2) : scanMsg;
        for (int i = mWaitLVAdaper.getCount()-1; i >= 0; i--) {
            RP_BorrowedTool item = mWaitLVAdaper.getItem(i);
            if(scanMsg.equals(item.getTool_id())){
                mWaitLVAdaper.deleteOne(i);
                mAlreadyLVAdaper.add(0,item);
                return;
            }
        }
        if(mAlreadyLVAdaper.getCount() == 0) {
            mScanLoadingDialog.dismiss();
        }
        ToastUtils.showLong("扫描工具不存在待归还列表");
    }



    /**
     * 请求网络接口获取民警信息
     *
     * @param scanStr
     */
    private void getPliceInfoFromSer(String scanStr) {
        scanStr = scanStr.indexOf("P") == 0 ? scanStr.substring(1) : scanStr;
        Request_loadPoliceInfo rq_lpi = new Request_loadPoliceInfo();
        rq_lpi.setCusNumber(SPUtils.getInstance("app_login").getString(Constance.SP_CUSNUMBER));
        rq_lpi.setPoliceCode(scanStr);
        //发送获取民警信息接口请求
        HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_LOAD_POLICE_INFO, rq_lpi, policeInfoCallback);
    }

    /**
     * 获取民警信息接口回调
     */
    private CustomNetCallBack policeInfoCallback = new CustomNetCallBack() {
        @Override
        public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
            LogUtils.e(data);
            Response_loadPoliceInfo loadPoliceInfo = mGson.fromJson(data, Response_loadPoliceInfo.class);
            if (loadPoliceInfo == null) {
                ToastUtils.showLong("接收人信息为空");
                return;
            }
            mScanLoadingDialog.dismiss();
            mPoliceInfo = loadPoliceInfo;
            TextViewUtil.setUnderLine(tv_jinban_person,mPoliceInfo.getPolice_name());
            //获取库存信息
            getFreeToolsCountFromSer();
            //接着扫描归还人
            scanAfterPolice();
        }

        @Override
        public void onErrorFromSer(int rtnCode, String rtnMsg) {
            ToastUtils.showLong("获取接收人信息失败");
        }

        @Override
        public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
            ToastUtils.showLong("获取接收人信息失败");
            LogUtils.e(ex);
        }
    };

    /**
     * 请求网络接口获取归还人信息
     *
     * @param scanStr
     */
    private void getPrisonerInfoFromSer(String scanStr) {
        scanStr = scanStr.indexOf("P") == 0 ? scanStr.substring(1) : scanStr;
        Request_loadPoliceInfo rq_lpi = new Request_loadPoliceInfo();
        rq_lpi.setCusNumber(SPUtils.getInstance("app_login").getString(Constance.SP_CUSNUMBER));
        rq_lpi.setPoliceCode(scanStr);
        //发送归还人（民警）信息接口请求
        HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_LOAD_POLICE_INFO, rq_lpi, prisonerInfoCallback);

    }



    /**
     * 获取归还人接口回调
     */
    private CustomNetCallBack prisonerInfoCallback = new CustomNetCallBack() {
        @Override
        public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
            LogUtils.e(data);
            Response_loadPoliceInfo loadPrisonerInfo = mGson.fromJson(data, Response_loadPoliceInfo.class);
            if (loadPrisonerInfo == null) {
                ToastUtils.showLong("归还人信息为空");
                return;
            }
            mScanLoadingDialog.dismiss();
            mGuiHuanPerson = loadPrisonerInfo;
            TextViewUtil.setUnderLine(tv_guihuan_person,loadPrisonerInfo.getPolice_name());

            getRecyclerToolsList();
            scanAfterPrison();
        }

        @Override
        public void onErrorFromSer(int rtnCode, String rtnMsg) {
            ToastUtils.showLong("获取归还人信息失败");
        }

        @Override
        public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
            ToastUtils.showLong("获取归还人信息失败");
            LogUtils.e(ex);
        }
    };






    @Event({R.id.bt_tool_recycler_next, R.id.bt_tool_recycler_end})
    private void onViewClick(View v) {
        switch (v.getId()) {
            case R.id.bt_tool_recycler_next:
                modifyToolStatus(R.id.bt_tool_recycler_next);
                break;
            case R.id.bt_tool_recycler_end:
                modifyToolStatus(R.id.bt_tool_recycler_end);
                break;
        }
    }



    /**
     * 调取接口获取待归还列表
     */
    private void getRecyclerToolsList() {
        RQ_RecyclerTool rq_getGrantedTools = new RQ_RecyclerTool();
        rq_getGrantedTools.setCus_number(mPoliceInfo.getCus_number() + "");
        rq_getGrantedTools.setRecive_dprt_id(mPoliceInfo.getDepartment_id() + "");
        rq_getGrantedTools.setReturn_dprt_id(mGuiHuanPerson.getDepartment_id() + "");
        HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_TOOL_GET_BORROWED_TOOL, rq_getGrantedTools, new CustomNetCallBack() {
            @Override
            public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
                List<RP_BorrowedTool> toolInfoList = mGson.fromJson(data, new TypeToken<ArrayList<RP_BorrowedTool>>() {
                }.getType());
                mWaitLVAdaper.clearAdd(toolInfoList);
                if (toolInfoList == null || toolInfoList.size() == 0) {
                    ToastUtils.showLong("没有待归还的工具");
                }
            }

            @Override
            public void onErrorFromSer(int rtnCode, String rtnMsg) {
                ToastUtils.showLong("获取待归还列表失败(" + rtnCode + "," + rtnMsg + ")");
            }

            @Override
            public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
                ToastUtils.showLong("获取待归还列表失败");
                LogUtils.e(ex.toString());
            }
        });
    }






    /**
     * 请求网络接口提交发放
     */
    private void modifyToolStatus(final int viewID) {
        if(mPoliceInfo == null){
            ToastUtils.showLong("请先获取民警信息");
            return;
        }
        switch (mToolSystemSet.getGive_object()){
            case RP_ToolSysSet.TSS_GIVE_OBJECT_PERSON:
                if(mGuiHuanPerson == null){
                    ToastUtils.showLong("请先获取归还人信息");
                    return;
                }
                break;
        }
        if(mAlreadyLVAdaper.getCount() <= 0){
            ToastUtils.showLong("请扫描归还工具");
            return;
        }

        RQ_Recycler_Return_Tool tool = new RQ_Recycler_Return_Tool();
        tool.tool_data = new ArrayList<>();
        RQ_Recycler_Return_Tool.MyToolInfo toolInfo = null;
        for(int i = 0; i < mAlreadyLVAdaper.getCount(); i++) {
            toolInfo = new RQ_Recycler_Return_Tool.MyToolInfo();
            RP_BorrowedTool rp_borrowedTool = mAlreadyLVAdaper.getItem(i);
            String borrow_record_id = rp_borrowedTool.getBorrow_record_id();
            String tool_id = rp_borrowedTool.getTool_id();
            toolInfo.borrow_record_id = borrow_record_id;
            toolInfo.tool_id = tool_id;

            tool.tool_data.add(toolInfo);
        }
        tool.cus_number = mPoliceInfo.getCus_number() + "";
        tool.return_person_id = mGuiHuanPerson.getPolice_id();
        tool.return_person_name = mGuiHuanPerson.getPolice_name();
        tool.recive_person_id = mPoliceInfo.getPolice_id();
        tool.recive_person_name = mPoliceInfo.getPolice_name();
        tool.status = "2";
        tool.out_dprt_id = mGuiHuanPerson.getDepartment_id() + "";
        tool.out_dprt_name = mGuiHuanPerson.getDepartment_name();
        tool.in_dprt_id = mPoliceInfo.getDepartment_id() + "";
        tool.in_dprt_name = mPoliceInfo.getDepartment_name();


        HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_TOOL_RETURN_TOOL, tool, new CustomNetCallBack() {
            @Override
            public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
                switch (viewID) {
                    case R.id.bt_tool_recycler_next:
                        ToastUtils.showLong("归还提交成功");
                        //TODO 清空本页面的信息
                        tv_guihuan_person.setText("");
                        mGuiHuanPerson = null;
                        tv_jinban_person.setText("");
                        mWaitLVAdaper.deleteAll();
                        mAlreadyLVAdaper.deleteAll();
                        scanAfterPolice();
                        //重新获取库存
                        getFreeToolsCountFromSer();
                        break;
                    case R.id.bt_tool_recycler_end:
                        new AlertDialog.Builder(ToolRecyclerActivity.this).setTitle("提示")
                                .setMessage("归还成功，本页面将关闭")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        ToolRecyclerActivity.this.finish();
                                    }
                                }).setCancelable(false).create().show();
                        break;
                }
            }

            @Override
            public void onErrorFromSer(int rtnCode, String rtnMsg) {
                ToastUtils.showLong("归还提交失败(" + rtnCode + "," + rtnMsg + ")");
            }

            @Override
            public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
                ToastUtils.showLong("归还提交失败");
                LogUtils.e(ex);
            }
        });
    }



    /**
     * 请求网络接口获取库存信息
     */
    private void getFreeToolsCountFromSer() {
        RQ_FreeCountTool freeCountTool = new RQ_FreeCountTool();
        freeCountTool.setCus_number(mPoliceInfo.getCus_number() + "");
        freeCountTool.setDprt_id(mPoliceInfo.getDepartment_id()+"");
        HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_TOOL_FREE_COUNT, freeCountTool, new CustomNetCallBack() {
            @Override
            public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
                LogUtils.e(data);
                List<RP_FreeCountTools> tempList = mGson.fromJson(data, new TypeToken<ArrayList<RP_FreeCountTools>>() {
                }.getType());
                mToolsStockAdapter.clearAdd(tempList);
                if (tempList == null || tempList.size() == 0) {
                    ToastUtils.showLong("库存信息为空");
                }
            }

            @Override
            public void onErrorFromSer(int rtnCode, String rtnMsg) {
                ToastUtils.showLong("获取库存信息失败(" + rtnCode + "," + rtnMsg + ")");
            }

            @Override
            public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
                ToastUtils.showLong("获取库存信息失败");
                LogUtils.e(ex);
            }
        });
    }




    /**
     * ====================================扫描流程=========================================
     */
    private void scanPolice() {
        //是否需要扫描民警
        if (RP_ToolSysSet.TSS_CALL_TYPE_SCAN_USER == (mToolSystemSet.getCall_type())) {
            //扫民警
            openScan(REQUEST_CODE_POLICE, mToolSystemSet, "请扫描接收人条码");
        } else if (RP_ToolSysSet.TSS_CALL_TYPE_LOGIN_USER == (mToolSystemSet.getCall_type())) {
            //使用登录民警信息
            mPoliceInfo = new Response_loadPoliceInfo();
            Response_login_user loginUser = MainApp.getInstance().getLoginUser();
            mPoliceInfo.setCus_number(loginUser.getCus_number());
            mPoliceInfo.setDepartment_id(loginUser.getDepartment_id());
            mPoliceInfo.setDepartment_name(loginUser.getDepartment_name());
            mPoliceInfo.setPolice_code(loginUser.getPolice_code());
            mPoliceInfo.setPolice_id(loginUser.getPolice_id());
            mPoliceInfo.setPolice_name(loginUser.getPolice_name());
            //接着扫描 归还人
            scanAfterPolice();
        }
    }

    //使用登录民警为接收人，扫描归还人
    private void scanAfterPolice() {
        //扫描借出人
        openScan(REQUEST_CODE_PRISONER, mToolSystemSet, "请扫描归还人");
    }


    //扫描归办人后 扫描工具
    private void scanAfterPrison() {
        //获取待归还工具列表
        getRecyclerToolsList();
        //扫描工具
        openScan(REQUEST_CODE_TOOLS, mToolSystemSet, "请扫描归还工具");
    }


    @Override
    public void onAlreadyLvDeleteClick(final int position) {
        new AlertDialog.Builder(this).setTitle("提示")
                .setMessage("是否取消归还此工具？")
                .setNegativeButton("取消", null)
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        RP_BorrowedTool item = mAlreadyLVAdaper.getItem(position);
                        mAlreadyLVAdaper.deleteOne(position);
                        mWaitLVAdaper.add(0, item);
                    }
                }).create().show();
    }
}
